import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:scrollview_observer/scrollview_observer.dart';
import 'package:ball_lion/module/home/comment_view_logic.dart';
import 'package:ball_lion/module/home/news_detail_logic.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/app_config.dart';
import 'package:ball_lion/utils/local_read_history.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/expert/items/plan_item.dart';
import 'package:ball_lion/module/home/comments/comment_input_widget.dart';
import 'package:ball_lion/module/home/comments/news_comments_view.dart';
import 'package:ball_lion/module/home/comments/news_share_append.dart';
import 'package:ball_lion/module/home/news_cell.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/share/share_sheet.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:ball_lion/module/home/news_detail_view.dart';
import 'package:ball_lion/module/home/post_cell.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class NewsDetailPage extends StatefulWidget {
  const NewsDetailPage({super.key});

  @override
  State<NewsDetailPage> createState() => _NewsDetailPageState();
}

class _NewsDetailPageState extends State<NewsDetailPage> {
  int id = "${Get.arguments}".toInt() ?? 0;
  late final NewsDetailLogic logic;
  late final CommentViewLogic commentLogic;

  late int? classId = int.tryParse(Get.parameters['classId'] ?? "");
  EasyRefreshController refreshC =
      EasyRefreshController(controlFinishLoad: true);

  // late final commentsController = NewsCommentsController(id ?? 0);
  final scrollC = ApmScrollController();
  bool showTop = false;

  late ListObserverController observerController;

  @override
  void initState() {
    super.initState();
    // commentsController.fetchCommentds();
    // AppNewsFloat2Widget.delNews(id);
    Utils.onEvent('zx_ck');
    logic = Get.put(NewsDetailLogic(), tag: '${Get.arguments}');
    commentLogic = Get.put(CommentViewLogic(), tag: '${Get.arguments}');
    LocalReadHistory.readNews("${logic.newsId}");
    observerController = ListObserverController(controller: scrollC);
    scrollC.addListener(() {
      if (scrollC.offset > 60 && showTop == false) {
        showTop = true;
        update();
      } else if (scrollC.offset < 60 && showTop == true) {
        showTop = false;
        update();
      }
    });
  }

  @override
  void dispose() {
    scrollC.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    bool loading = logic.data.toString().isEmpty;

    if (loading) {
      return const CircularProgressIndicator();
    } else {
      return GetBuilder<NewsDetailLogic>(
        tag: '$id',
        builder: (_) => Scaffold(
          resizeToAvoidBottomInset: false,
          backgroundColor: Colours.N1,
          appBar: Styles.appBar(
              titleSpacing: 0,
              // toolbarHeight: kToolbarHeight,
              // title: Image.asset(Utils.getImgPath("qxb_title.png")),
              title: showTop
                  ? Styles.userAppbarTitle(
                      logo: logic.data?.logo,
                      name: logic.data?.publisherName,
                      focus: logic.data?.focus,
                      userId: logic.data?.publisherId,
                      onTap: (value) => logic.getNews())
                  : const QsText('内容详情'),
              actions: [
                GestureDetector(
                  onTap: () async {
                    Utils.onEvent("zxxq", params: {"zxxq": 1});
                    final news = logic.data;
                    final classId = logic.classId;
                    if (news == null) {
                      return;
                    }
                    Get.bottomSheet(
                        ShareSheet(
                            append:
                                NewsShareAppend(news: news, classId: classId)),
                        settings: RouteSettings(
                            arguments:
                                ShareEntity(url: 'tg/articles/${news.id}')));
                  },
                  child: SizedBox(
                    height: Get.height,
                    child: Image.asset(
                      Utils.getImgPath("news_detail_more.png"),
                      width: 24,
                      height: 24,
                    ).marginOnly(right: 16),
                  ),
                )
              ]),
          body: LoadingWidget<bool>(
            isLoading: logic.data == null,
            reconnect: logic.getRefresh,
            data: logic.data?.id == null,
            child: () => Column(
              children: [
                Expanded(
                  child: ListViewObserver(
                    controller: observerController,
                    child: ListView(controller: scrollC, children: [
                      Column(
                        children: [
                          logic.data?.type == 2
                              ? PostCell(
                                  logic.data!,
                                  type: 1,
                                )
                              : NewsDetailView(data: logic.data),
                          ...logic.plan
                                  ?.map((e) => Block(
                                      cardStyle: const CardStyle(
                                          margin:
                                              EdgeInsets.fromLTRB(8, 8, 8, 0),
                                          padding: EdgeInsets.symmetric(
                                              horizontal: 12)),
                                      child: PlanItem(
                                        entity: e,
                                        eventType: "zx_ckfa",
                                      )))
                                  .toList() ??
                              [],
                          if (logic.data?.list?.hasValue == true &&
                              AppConfig.config.showRelative)
                            recommendNews(),
                        ],
                      ),
                      Container(
                          color: Colours.scaffoldBg,
                          padding: const EdgeInsets.only(top: 8),
                          constraints: BoxConstraints(
                              minHeight: Get.height -
                                  MediaQuery.of(context).padding.top -
                                  -MediaQuery.of(context).padding.bottom -
                                  384),
                          child: GetBuilder<CommentViewLogic>(
                            tag: '$id',
                            builder: (_) {
                              return NewsCommentsView(id,
                                  paddingTop:
                                      MediaQuery.of(context).padding.top);
                            },
                          ))
                    ]),
                  ),
                ),
                SafeArea(
                    top: false,
                    child: GetBuilder<CommentViewLogic>(
                      tag: '$id',
                      builder: (_) {
                        return Container(
                          color: Colours.white,
                          child: CommentInputWidget(
                              afterShare: () => update(),
                              canInput: (bool isbtn) {
                                if (isbtn) {
                                  if (scrollC.offset == 0) {
                                    Future.delayed(
                                            const Duration(milliseconds: 100))
                                        .then((value) {
                                      observerController.animateTo(
                                          index: 1,
                                          duration:
                                              const Duration(milliseconds: 200),
                                          curve: Curves.linear);
                                    });
                                    return false;
                                  } else {
                                    scrollC.animateTo(0,
                                        duration:
                                            const Duration(milliseconds: 200),
                                        curve: Curves.linear);
                                    return false;
                                  }
                                }
                                return true;
                              },
                              news: logic.data,
                              newsId: id,
                              cid: classId,
                              textId: "$id"),
                        );
                      },
                    ))
              ],
            ),
          ),
        ),
      ).tap(() {
        FocusScope.of(context).unfocus();
      });
    }
  }

  Widget recommendNews() {
    return Container(
      color: Colours.scaffoldBg,
      // padding: const EdgeInsets.only(top: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          QsText(
            "相关资讯",
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ).marginOnly(top: 12, left: 16),
          ...List.generate(
              logic.data!.list!.length,
              (index) => NewsItemCell(
                    logic.data!.list![index],
                    classId: classId,
                    inHome: false,
                    imgStyle: logic.data!.list![index].imgStyle,
                    bottomDivider: index != logic.data!.list!.length - 1,
                    afterRoute: () => update(),
                    onTap: () => Utils.onEvent('zxxq', params: {'zxxq': 4}),
                  )),
          // ...recommendList.map((e) => NewsListCell(e,classId: classId,inHome: false,afterRoute: () => update(),))
        ],
      ),
    );
  }
}
